<?php

namespace app\common\model;

use think\Db;
use think\Model;


class StockWarning extends Model
{

    

    

    // 表名
    protected $name = 'stock_warning';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'area_text',
	    'level_text'
    ];
    
	public function getAreaTextAttr($value, $data) {
		$value = $value ? : $data['area'];
		$list = \app\admin\model\User::$areaList;
		return $list[$value] ?? '';
	}
	
	public function getLevelTextAttr($value, $data) {
		$value = $value ? : $data['level'];
		$list = \app\admin\model\User::$levelList;
		return $list[$value] ?? '';
	}
    

	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function spec() {
		return $this->belongsTo('goodsSpec', 'spec_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	/**
	 * 检测发货数量是否超过设置数量
	 * @param $goodsId
	 * @param $specId
	 * @param $agentId
	 * @param $number
	 * @param $area
	 * @param $role
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbExceptions
	 * @throws \think\exception\DbException
	 */
	public function checkSendMaxNumer($goodsId, $specId, $agentId, $number, $area, $role)
	{
		
		//查找商品名称，方便提示
		$goods = Db::name('goods')->alias('g')
			->join('goodsSpec s', 'g.id = s.goods_id and s.id = ' . $specId, 'left')
			->where(['g.id' => $goodsId])
			->field('g.name, s.name as spec_name')
			->find();
		
		$goodsName = ($goods['spec_name'] ?: '') . $goods['name'];
		
		$model = new AgentStock();
		$count = $model->getAgentAndSubStock($agentId, $goodsId,$specId);
		$maxNumber = $count ? $count['all_max_stock'] - $count['all_stock'] : 0;

		if ($number <= $maxNumber) {
			return true;
		} else {
			$this->error = $goodsName . '发货超出最大库存'.$maxNumber;
			return false;
		}
		
		//当前库存
		$stock = Db::name('agentStock')
			->where(['agent_shop_id' => $agentId, 'goods_id' => $goodsId, 'spec_id' => $specId])
			->find();
		
		$stockNumber = $stock ? $stock['number'] : 0;
		$maxNumber = 0;
		
		//看看有没单独的设置
		$agentSetting = Db::name('agentStockSetting')
			->where(['agent_id' => $agentId, 'goods_id' => $goodsId, 'spec_id' => $specId])
			->find();
		if ($agentSetting) {
			$maxNumber = $agentSetting['number'];
		} else {
			//全局设置
			$setting = Db::name('stockWarning')
				->where(['area' => $area, 'level' => $role, 'goods_id' => $goodsId, 'spec_id' => $specId])
				->find();
			if ($setting) {
				$maxNumber = $setting['number'];
			}
		}
		
		if ($stockNumber + $number <= $maxNumber) {
			return true;
		} else {
			$this->error = $goodsName . '发货超出最大库存';
			return false;
		}
	}
}
